#!/usr/bin/env python
# $Id: googleauth.py 312eedc3abd6 2012/09/23 00:20:44 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File googleauth.py generated on Saturday September 22, 2012 @ 01:49:37 PDT
#

__version__  = "$Revision: 312eedc3abd6 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-23 00:20:44Z $"

import getpass
import optparse
import os
import sys
import urllib2
import urllib

from venya.lib import exception, cmdparser, stdlib

class Auth(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-u", "--username", type = "str",
            help = "Username to authenticate", default = getpass.getuser(),
            dest = "username"),
         optparse.make_option("-d", "--domain", type = "str",
            help = "Domain managed by Google apps", dest = "domain"),
   ) + cmdparser.GetOpt.option_list

   usage = "[ options ]"

   def __init__(self, *args, **kwargs):
      super(Auth, self).__init__(*args, **kwargs)
      self._opener = urllib2.OpenerDirector()
      self._username = None
      self._password = None
      self._domain = None
      self._auth = None

      self._opener.add_handler(urllib2.ProxyHandler())
      self._opener.add_handler(urllib2.UnknownHandler())
      self._opener.add_handler(urllib2.HTTPHandler())
      self._opener.add_handler(urllib2.HTTPDefaultErrorHandler())
      self._opener.add_handler(urllib2.HTTPErrorProcessor())
      self._opener.add_handler(urllib2.HTTPSHandler())

   def authenticate(self):
      if self._username and self._password:
         authuri = "https://www.google.com/accounts/ClientLogin"
         authreqdata = urllib.urlencode({
            "Email"       : self._username,
            "Passwd"      : self._password,
            "service"     : "ah",
            "source"      : stdlib.my_class(self),
            "accountType" : "HOSTED_OR_GOOGLE" })

         req = urllib2.Request(authuri, data = authreqdata)
         try:
            response = self._opener.open(req)
            respbody = response.read()
            respdict = dict(ix.split("=") for ix in respbody.split("\n") if ix)
            self._auth = respdict["Auth"]
         except urllib2.HTTPError as err:
            if err.code == 403:
               raise ValueError(
                     "%s authentication failed with code %d error %s" %(
                        self._username, err.code, err.msg))

   @cmdparser.getopts
   def handle(self):
      if self.options.username:
         self._username = self.options.username.strip()

      if self.options.domain:
         self._username = "%s@%s" %(self._username, self.options.domain.strip())

      self._password = getpass.getpass(
            "Enter Google password for %s: " %self._username)
      try:
         self.authenticate()
      except ValueError as err:
         self.error(err)
      else:
         if self.options.verbosity:
            print("%s authentication successfully" %self._username)

if __name__ == "__main__":
   gauth = None
   try:
      gauth = Auth(version = 1.0, args = sys.argv)
      if gauth.length <= 1:
         gauth.printhelp()
      else:
         gauth.handle()
   except exception.GetOptError as err:
      print(err)
      sys.exit(1)
